//合同变更 
public without sharing class ContractModifyController {
	public String msg {get;private set;}
	public Boolean isErr {get; private set;}//错误
	public Boolean isSuccess {get; private set;}//是否保存成功

    public Boolean cnnotEdit {get; private set;}//是否保存成功

	public String backId {get; private set;}
	public class ControllerException extends Exception {}

	public String dataJson {get; private set;}
	public String saveJson {get; set;}
	public String searchJson {get; set; }

	private Set<String> pset; 
	private Boolean isNew;
	public String oppId {get;private set;} 
    private  Map<String,DataUtil.SObjectBean> stageObjectMap;

	private Contract__c mcon; //变更的合同

    private String accId ;//客户id 
    private Boolean isBM ;//是不是大家 
    private String  isSystem;//是不是体系



    public ContractModifyController() {
        backId = System.currentPageReference().getParameters().get('id');
        isNew = false;
        cnnotEdit = false;
        pset = new Set<String>();
        stageObjectMap = new  Map<String,DataUtil.SObjectBean>();

    }
    private void setErr(String message){
    	isErr  =true;
    	throw new ControllerException(message);
    }
    public void setNil(){
    	dataJson = '[]';



    }

    public void init(){

    	try {
    	    if(backId == null)setErr('页面打开错误!');
    	    Contract__c con = new Contract__c();

    	   if(Id.valueOf(backId).getSObjectType() == Opportunity.SObjectType ){//新建
                
                Opportunity opp = [select Id,Account.System__c  , AccountId from Opportunity where Id =: backId ];
                    mcon = new Contract__c();
                    mcon.Account__c = opp.AccountId ;
                    mcon.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('ChangeContract', 'Contract__c');
                    mcon.ApproveType__c = '2';
                    isNew = true;
                    oppId = con.Opportunity__c;
                    isBM = opp.Account.System__c  == '大家检验';
                    accId = opp.AccountId;


            }else{
                
                con = [select Id,AllProducts__c ,Name ,Status__c,Opportunity__c,Account__r.System__c ,MainContract__r.Name ,MainContract__c ,MainContract__r.Account__c ,RecordType.DeveloperName ,Vsalestrucode__c,Corpcode__c ,CooperationType__c,
                Account__c,Maccura__c,CustomerContact__c,ChangeContractProduct__c,MainContract__r.Opportunity__c,ContractSource__c,OASeal__c,MainContract__r.Status__c  ,MainContract__r.AllProducts__c ,MainContract__r.Account__r.System__c
                from Contract__c where Id=:backId];

                isBM = con.Account__r.System__c  == '大家检验';

                if(con.RecordType.DeveloperName == 'ChangeContract'){//编辑

                    if(con.MainContract__r.AllProducts__c)isSystem =con.MainContract__r.Account__r.System__c  ;

                    mcon = con;
                    oppId = con.MainContract__r.Opportunity__c;
                    //if(con.Status__c != '草稿' && con.Status__c != 'OA已拒绝' && con.Status__c != 'SF审批拒绝' && con.Status__c != '已生效'   )setErr('合同变更审批中不能修改!');
                    if(con.MainContract__r.Status__c != '已生效')setErr('主合同未生效不能变更!');

                    if(con.Status__c == '已推送OA' ||con.Status__c == 'OA审批中' ||con.Status__c == '已生效'||con.Status__c== 'SF审批中' ||con.Status__c== 'SF审批成功')cnnotEdit = true;
                    accId = con.Account__c;

                }else if(con.RecordType.DeveloperName != 'ChangeContract' && con.RecordType.DeveloperName != 'DeleteContract' ){//新建

                    if(con.AllProducts__c)isSystem =con.Account__r.System__c  ;
                    if(con.Status__c != '已生效')setErr('主合同未生效不能变更!');
                    mcon = new Contract__c();
                    mcon.MainContract__c = con.Id;
                    // mcon.ContractSource__c = con.ContractSource__c;
                    // //mcon.Name = ;
                    // mcon.Vsalestrucode__c = con.Vsalestrucode__c;
                    // mcon.Corpcode__c = con.Corpcode__c;
                    // mcon.CooperationType__c = con.CooperationType__c;
                     mcon.Account__c = con.Account__c;





                    // mcon.Maccura__c = con.Maccura__c;
                    // mcon.CustomerContact__c = con.CustomerContact__c;
                    mcon.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('ChangeContract', 'Contract__c');
                    mcon.ApproveType__c = '2';
                    isNew = true;
                    oppId = con.Opportunity__c;
                    //ChangeContractProduct__c

                }
            }
            

    	   accId =  mcon.Account__c;

    	    Map<String,Object> dataMap = new Map<String,Object>();
        	
        	dataMap.put('detail', getDetails());
        	//dataMap.put('search', getProductFromContract());
            dataMap.put('coop', getProductFromCoop());

            getProductFromContract(dataMap);

			dataMap.put('combobox',getCombox('ContractChangeList__c',new Set<String>{'AlterType__c','CooperateType__c','WhetherAddInstrument__c','EnterWay__c'}));
    	   	dataMap.put('searchObject',getSearchObject());

                    //字段
             Map<String,Set<String>> fieldsmap = getFields();
             //字段详情
             Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
            
            //字段赋值
             Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
                         

            dataMap.put('base',fields);

             for (DataUtil.FieldBean fb   :  fields.get('Contract__c')) {
                Map<String,Object> vMap  = new Map<String,Object>();
                if(fb.name == 'MainContract__c'){
                    vMap.put('Id', isNew ?  con.Id : mcon.MainContract__c  );
                    vMap.put('Name', isNew ?  con.Name  : mcon.MainContract__r.Name  );
                    fb.value = vMap;
                }
            }
            dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap)); 

        	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap ),'UTF-8');


    	}
    	catch (Exception e) {
            isErr = true;
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    	}
    	
    }

     public Map<String,Set<String>>  getFields(){
        Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
        
            DataUtil.SObjectBean sb = new DataUtil.SObjectBean();
            sb.title ='';
            sb.objname = 'Contract__c';
            sb.stype = DataUtil.getSObjectType('Contract__c');
            if(!isNew)sb.idvalue = mcon.Id;
            sb.type = 'base';
            if(!isNew)sb.condition = ' where Id =\''+mcon.Id+'\'';
            stageObjectMap.put('Contract__c',sb );
            Set<String>  fields = new Set<String>{'ContractSource__c','ChangeContractProduct__c','Compensation__c','MainContract__c'};
         
            fieldsMap.put('Contract__c', fields);
        
        return fieldsMap;
    }

     private Map<String ,Map<String,String>> getCombox(String objName ,Set<String> fields ){
    	Map<String ,Map<String,String>> tmp = new Map<String ,Map<String,String>>();
    	for(String f : fields){
    		Map<String,String> pickMap = ImportObject.getPicklistValues(objName, f, true);
    		tmp.put(f, pickMap);
    	}
    	return tmp;
    } 

     private Map<String,List<DataUtil.FieldBean>> getSearchObject(){
    	Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

    	Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Product__c.SObjecttype, new Set<String>{'ProductName__c','Brand__c','Spec__c','Model__c','NCCode__c','SerialNo__c','Category0__c','Category1__c'} );
    	searchMap.put('Product__c', proMap.values());
    	return searchMap;
    }

    public void searchContract(){

        Map<String,Object> searchMap = (Map<String,Object> ) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

        String sql = ' select Id,Name,ContractNum__c, Account__c,Account__r.Name ,Maccura__c ,Maccura__r.Name , StartDate__c, EndDate__c   from Contract__c where Status__c = \'已生效\' and  RecordType.DeveloperName =  \'TerminalContract\' ';
        sql +=  isBM ? ' and (Account__c = \''+accId+'\'   or  (Account__r.System__c = \'大家检验\' and AllProducts__c = true ) ) '  : ' and Account__c = \''+accId+'\' ' ;

        if(searchMap.get('Name') != null && String.isNotBlank((String)searchMap.get('Name'))) sql += ' and Name like \'%'+searchMap.get('Name')+'%\' ';
        if(searchMap.get('ContractNum__c') != null && String.isNotBlank((String)searchMap.get('ContractNum__c'))) sql += ' and ContractNum__c like \'%'+searchMap.get('ContractNum__c')+'%\' ';
        
        List<Object> tmp = new List<Object>();
        System.debug(sql);

        for(Contract__c c : Database.query(sql)){
            Map<String,Object> m = new Map<String,Object>();
            m.put('Id', c.Id );
            m.put('Name', c.Name );
            m.put('ContractNum__c', c.ContractNum__c);
            m.put('Account', c.Account__r.Name );
            m.put('Maccura', c.Maccura__r.Name );
            m.put('StartDate__c', c.StartDate__c );
            m.put('EndDate__c', c.EndDate__c );
            tmp.add(m);
        }
        dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp ),'UTF-8');
    }
    /*
    public void searchProduct(){

    	Map<String,Object> searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));
         String sealflag  =  'Y-'+ mcon.Corpcode__c;

    	String sql = ' select Id  ,ProductName__c ,SerialNo__c , Brand__c ,Spec__c,Category0__c,NCCode__c ,Category1__c ,SealCompany__c,MatchingInstrument__c,NCinvshortname__c  from Product__c where  Createddate != null ';
    	sql += ' and Id  not in (select Product__c from ContractProduct__c where Contract__c =\''+mcon.MainContract__c+'\'  ) and  (not SealCompany__c  like \'%'+sealflag+'%\') ';

    	sql += ' and Category0__c = \'仪器\'  and PriceCompany__c like \'%'+ mcon.Corpcode__c+'%\' ';
    	
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('ProductName__c'))) == false) sql += ' and ProductName__c like \'%'+DataUtil.getStringValue(searchMap.get('ProductName__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Brand__c'))) == false) sql += ' and Brand__c like \'%'+DataUtil.getStringValue(searchMap.get('Brand__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Spec__c'))) == false) sql += ' and Spec__c like \'%'+DataUtil.getStringValue(searchMap.get('Spec__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('SerialNo__c'))) == false) sql += ' and SerialNo__c like \'%'+DataUtil.getStringValue(searchMap.get('SerialNo__c'))+'%\' ';
 
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category0__c'))) == false) sql += ' and Category0__c like \'%'+DataUtil.getStringValue(searchMap.get('Category0__c'))+'%\' ';
        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category1__c'))) == false) sql += ' and Category1__c like \'%'+DataUtil.getStringValue(searchMap.get('Category1__c'))+'%\' ';
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('NCCode__c'))) == false) sql += ' and NCCode__c like \'%'+DataUtil.getStringValue(searchMap.get('NCCode__c'))+'%\' ';

    	sql += ' limit 200 ';
    	System.debug('ContractModifyController==>'+sql);
    	  List<ModifyBean> tmp = new List<ModifyBean>();
          Set<Id> psets = new Set<Id>();
	      for(Product__c p : Database.query(sql)){
            psets.add(p.Id);
	      	 tmp.add(new ModifyBean(p));

	      }
          //带配套的产品
          for(Product__c p : [select Id  ,ProductName__c ,SerialNo__c , Brand__c ,Spec__c,Category0__c,NCCode__c ,NCinvshortname__c,
            Category1__c ,SealCompany__c,MatchingInstrument__c  from Product__c where MatchingInstrument__c in: psets]){
             tmp.add(new ModifyBean(p));

          }


	      dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');


    }
 */
    public List<ModifyBean> getProductFromContract(Map<String,Object>dataMap ){
    	List<ModifyBean> tmp = new List<ModifyBean>();
        List<ModifyBean> tmp1 = new List<ModifyBean>();

    	for (ContractProduct__c cp : [select Id ,Product__c ,CoopType__c,Product__r.ProductName__c,Product__r.Spec__c,Product__r.NCCode__c,
    		SalesPrice__c,Quantity__c,DeliveryQuantity__c,Measure_Calculate_Product__r.Measure_Calculate__r.Name,Product__r.NCinvshortname__c,
    		QuoteProduct__r.Quote__r.Name,InstrumentPolicy__r.InstrumentPolicy__r.Name,Product__r.Category1__c,Product__r.Brand__c,
            QuoteProduct__r.Quote__c ,  InstrumentPolicy__r.InstrumentPolicy__c,Measure_Calculate_Product__r.Measure_Calculate__c ,
            Opportunity__r.OppNo__c,Contract__c,EndCustomer__r.Name,Opportunity__r.Name ,
            BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name ,BloodSugarOrderDetail1__r.BloodSugarOrder__c,EnterWay__c, Product__r.Category0__c

    		from ContractProduct__c where Contract__c =: mcon.MainContract__c  ]) {
            ModifyBean m = new ModifyBean(cp);
    		if(cp.DeliveryQuantity__c > 0 ) tmp.add(m);
            tmp1.add(m);

    	}
        dataMap.put('search',tmp);
        dataMap.put('search_cp',tmp1);

    	return tmp;

    }
   
    public List<ModifyBean> getProductFromCoop(){
        List<ModifyBean> tmp = new List<ModifyBean>();


        if(isSystem != null ){

            for (ContractProduct__c cp : [select Id ,Product__c ,CoopType__c,Product__r.ProductName__c,Product__r.Spec__c,Product__r.NCCode__c,
                SalesPrice__c,Quantity__c,DeliveryQuantity__c,Measure_Calculate_Product__r.Measure_Calculate__r.Name,Product__r.NCinvshortname__c,
                QuoteProduct__r.Quote__r.Name,InstrumentPolicy__r.InstrumentPolicy__r.Name,Product__r.Category1__c,Product__r.Brand__c,
                QuoteProduct__r.Quote__c ,  InstrumentPolicy__r.InstrumentPolicy__c,Measure_Calculate_Product__r.Measure_Calculate__c ,
                 Opportunity__r.OppNo__c,Contract__c,EndCustomer__r.Name,Opportunity__r.Name ,
                BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name ,BloodSugarOrderDetail1__r.BloodSugarOrder__c,EnterWay__c, Product__r.Category0__c

                from ContractProduct__c where  Contract__c =null and  Opportunity__r.Account.System__c =:isSystem   and Id not in (select ContractProduct__c  from ContractChangeList__c where  ContractProduct__c != null and  Contract__r.Account__c  =: mcon.Account__c) ]) {


                tmp.add(new ModifyBean(cp));
            }
        }else{
            for (ContractProduct__c cp : [select Id ,Product__c ,CoopType__c,Product__r.ProductName__c,Product__r.Spec__c,Product__r.NCCode__c,
                SalesPrice__c,Quantity__c,DeliveryQuantity__c,Measure_Calculate_Product__r.Measure_Calculate__r.Name,Product__r.NCinvshortname__c,
                QuoteProduct__r.Quote__r.Name,InstrumentPolicy__r.InstrumentPolicy__r.Name,Product__r.Category1__c,Product__r.Brand__c,
                QuoteProduct__r.Quote__c ,  InstrumentPolicy__r.InstrumentPolicy__c,Measure_Calculate_Product__r.Measure_Calculate__c ,
                 Opportunity__r.OppNo__c,Contract__c,EndCustomer__r.Name,Opportunity__r.Name ,
                BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name ,BloodSugarOrderDetail1__r.BloodSugarOrder__c,EnterWay__c, Product__r.Category0__c

                from ContractProduct__c where  Contract__c =null and  CoCustomer__c =: mcon.Account__c and Id not in (select ContractProduct__c  from ContractChangeList__c where  ContractProduct__c != null and  Contract__r.Account__c  =: mcon.Account__c) ]) {


                tmp.add(new ModifyBean(cp));
            }
        }

        
        return tmp;

    }
    public Map<String,List<ModifyBean>>  getDetails (){

    	Map<String,List<ModifyBean>> tmpmap  = new Map<String,List<ModifyBean>>();
    	List<ModifyBean> changetmp = new List<ModifyBean>();
    	List<ModifyBean> addtmp = new List<ModifyBean>();
    	if(mcon.Id != null ){

    		for (ContractChangeList__c ccl  :
    			[select Id,Product__c,ContractProduct__c,ContractProduct__r.Product__c  ,AlterType__c,EnterWay__c,
    			ChangeQuantity__c,CooperateType__c,ContractProduct__r.Quantity__c,ContractProduct__r.Product__r.Category1__c,Product__r.Category1__c,
    			ContractProduct__r.DeliveryQuantity__c ,Reason__c ,ContractProduct__r.SalesPrice__c,WhetherAddInstrument__c,
    			SalesPrice__c,AdjustSalesPrice__c , ContractProduct__r.Measure_Calculate_Product__r.Measure_Calculate__r.Name ,
    			ContractProduct__r.QuoteProduct__r.Quote__r.Name,ContractProduct__r.InstrumentPolicy__r.InstrumentPolicy__r.Name,
    			ContractProduct__r.Product__r.ProductName__c,ContractProduct__r.Product__r.Spec__c,ContractProduct__r.Product__r.NCCode__c,
    			RelatedMeasure__c,RelatedMeasure__r.Name , ContractProduct__r.Product__r.MatchingInstrument__c,
    			Product__r.ProductName__c,Product__r.Spec__c,Product__r.NCCode__c,Product__r.NCinvshortname__c,
                ContractProduct__r.QuoteProduct__r.Quote__c ,  ContractProduct__r.InstrumentPolicy__r.InstrumentPolicy__c,
                ContractProduct__r.Measure_Calculate_Product__r.Measure_Calculate__c ,Product__r.Category0__c,
                ContractProduct__r.Opportunity__r.OppNo__c,ContractProduct__r.Opportunity__r.Name,CoopInstrumentsNew__c,CoopInstrumentsNew__r.Name,
                ContractProduct__r.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name ,ContractProduct__r.BloodSugarOrderDetail1__r.BloodSugarOrder__c,

                CoopInstrumentsNew__r.CoopType__c,CoopInstrumentsNew__r.Quantity__c,
                CoopInstrumentsNew__r.QuoteProduct__r.Quote__c ,CoopInstrumentsNew__r.QuoteProduct__r.Quote__r.Name ,
                CoopInstrumentsNew__r.Measure_Calculate_Product__r.Measure_Calculate__c ,CoopInstrumentsNew__r.Measure_Calculate_Product__r.Measure_Calculate__r.Name ,
                CoopInstrumentsNew__r.InstrumentPolicy__r.InstrumentPolicy__c ,CoopInstrumentsNew__r.InstrumentPolicy__r.InstrumentPolicy__r.Name ,
                CoopInstrumentsNew__r.BloodSugarOrderDetail1__r.BloodSugarOrder__c  ,CoopInstrumentsNew__r.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name 

    			 from  ContractChangeList__c where Contract__c =: mcon.Id ] ) {

    			if(ccl.AlterType__c == '新增合同仪器' || ccl.AlterType__c == '合作形式/价格变更' ){
    				addtmp.add(new ModifyBean(ccl));
    			}else{
    				changetmp.add(new ModifyBean(ccl));
    			}
    			
    		}
 
    	}
    	tmpmap.put('change',changetmp);
    	tmpmap.put('add',addtmp);
    	return tmpmap;
    }

    public void save(){
    		msg = '';
    	try {

    		Map<String , Object> saveMap = (Map<String ,Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson,'UTF-8'));
    	    
            Map<String,Object> baseMap = (  Map<String,Object>)saveMap.get('base');
                System.debug('ContractModifyController==> '+ baseMap );

            Map<String,Set<String>> fieldsMap = getFields();
            Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(Contract__c.SObjecttype,fieldsMap.get('Contract__c'));
            for(String field : baseMap.keySet()){

                if(baseMap.containsKey(field)){
                    System.debug(field +' '+ DataUtil.dataHandler(baseMap.get(field),fbeanMap.get(field).type.toUpperCase() ));
                    mcon.put(field, DataUtil.dataHandler(baseMap.get(field),fbeanMap.get(field).type.toUpperCase() ));
                }
            }


            List<Object> saveList = (List<Object>)saveMap.get('datas');
    		List<ContractChangeList__c> cclList  = new List<ContractChangeList__c>();
    		Set<String> cclsets = new Set<String>();
    		for(Object o : saveList){
    			Map<String,Object> mo = (Map<String,Object>) o ;
    			ContractChangeList__c ccl = new ContractChangeList__c();
    			ccl.Id = DataUtil.getStringValue(mo.get('Id'));
    			ccl.ContractProduct__c = DataUtil.getStringValue(mo.get('cpId'));
    			ccl.Product__c = DataUtil.getStringValue(mo.get('productId'));
    			ccl.ChangeQuantity__c = DataUtil.getDecimalValue(mo.get('num'));
    			ccl.CooperateType__c =  DataUtil.getStringValue(mo.get('cooptype'));

    			ccl.AlterType__c = DataUtil.getStringValue(mo.get('changetype'));
    			ccl.AdjustSalesPrice__c = DataUtil.getDecimalValue(mo.get('adprice'));
                ccl.SalesPrice__c  = DataUtil.getDecimalValue(mo.get('originPrice'));
                ccl.ProductLine__c = DataUtil.getStringValue(mo.get('cate1'));
    			ccl.Reason__c = DataUtil.getStringValue(mo.get('reason')); 
    			ccl.WhetherAddInstrument__c = DataUtil.getStringValue(mo.get('ismcadd')); 
    			ccl.RelatedMeasure__c =  DataUtil.getStringValue(mo.get('relatedMcId'));
                ccl.EnterWay__c = DataUtil.getStringValue(mo.get('enterway'));
                ccl.OriginalQuantity__c =  DataUtil.getDecimalValue(mo.get('originnum'));

                ccl.CoopInstrumentsNew__c = DataUtil.getStringValue(mo.get('relatedCoopId'));
                
    			if(ccl.Id != null ) cclsets.add(ccl.Id);
    			cclList.add(ccl);
    		}

    		SavePoint sp = Database.setSavepoint();
    		try {

                   Contract__c con =  [select Id ,ContractSource__c, Vsalestrucode__c,Corpcode__c,CooperationType__c,Account__c,Maccura__c,CustomerContact__c  from Contract__c where Id =:mcon.MainContract__c  ];
                   // mcon.ContractSource__c = con.ContractSource__c;
                    mcon.Vsalestrucode__c = con.Vsalestrucode__c;
                    mcon.Corpcode__c = con.Corpcode__c;
                    mcon.CooperationType__c = con.CooperationType__c;
                    mcon.Account__c = con.Account__c;
                    mcon.Maccura__c = con.Maccura__c;
                    mcon.CustomerContact__c = con.CustomerContact__c;



    			upsert mcon;
    			System.debug('ContractModifyController==> '+ cclsets );
    			delete [select Id from ContractChangeList__c where Contract__c =:mcon.Id  and Id not in: cclsets  ];
    			for (ContractChangeList__c ccl  : cclList) {
    				
    				if(ccl.Id == null )ccl.Contract__c = mcon.Id;
    			}
    			if(cclList.size() > 0 ) upsert cclList;

    		    msg = '保存成功!';

    			isSuccess = true;
    			backId = mcon.Id;
    		}catch (Exception e) {
    			if(isNew) mcon.Id = null;
    			
    		    Database.rollback(sp);
    		    msg = ' 保存失败:'+ e.getMessage()+e.getStackTraceString();
    		}
    		



    	}catch(Exception e ){

    		msg = ' 保存失败:'+ e.getMessage()+e.getStackTraceString();
    	}
        System.debug(msg);

    }


    public class ModifyBean{

    	public String Id;
    	public String cpId;//合同仪器Id 
    	public String productId;
    	public String productName;

        public String shortName ; 
    	public String spec;//仪器型号
    	public String nccode;
        public String cate1 ; 
    	public String cooptype ;//合作类型
    	public String changetype; //变更类型
        public String brand ;

        public String cate0;
        public String enterway;

    	public Decimal num; //变更数量
    	public Decimal originnum ; //原签约数
    	public Decimal cannum;//可变更数
        public String oppName ;
        public String oppNo ;

    	public String quoteId ;
    	public String mcId;
    	public String policyId;
        public String bloodId ;

    	public Decimal originPrice;//原价格
    	public Decimal adprice;//现价格

    	public String reason ;//原因
        public String termial;//EndCustomer__c


    	public String ismcadd;
    	public String relatedMcId;//关联测算
    	public String relatedMcName; //关联测算
    	public String relateName;///

        public String relatedId ; //配套仪器Id 

        public String relatedCoopId ; //关联原合同仪器
        public String relatedCoopName ; //关联原合同仪器


        public String  o_relateName;
        public Decimal o_num;
        public String originId;
        public String o_cooptype;


    	public ModifyBean(ContractChangeList__c ccl ){
    		Id = ccl.Id;
    		productId = ccl.Product__c;
    		cpId = ccl.ContractProduct__c;
            relatedCoopId = ccl.CoopInstrumentsNew__c;
            relatedCoopName = ccl.CoopInstrumentsNew__r.Name;

             
            if(ccl.CoopInstrumentsNew__r.QuoteProduct__r.Quote__r.Name != null )o_relateName =ccl.CoopInstrumentsNew__r.QuoteProduct__r.Quote__r.Name;
            if( ccl.CoopInstrumentsNew__r.Measure_Calculate_Product__r.Measure_Calculate__r.Name != null )o_relateName = ccl.CoopInstrumentsNew__r.Measure_Calculate_Product__r.Measure_Calculate__r.Name;
            if(ccl.CoopInstrumentsNew__r.InstrumentPolicy__r.InstrumentPolicy__r.Name != null )o_relateName =ccl.CoopInstrumentsNew__r.InstrumentPolicy__r.InstrumentPolicy__r.Name;
            if(ccl.CoopInstrumentsNew__r.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name  != null ) o_relateName = ccl.CoopInstrumentsNew__r.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name;

            o_num = ccl.CoopInstrumentsNew__r.Quantity__c;
            
            if(ccl.CoopInstrumentsNew__r.QuoteProduct__r.Quote__c != null )originId =ccl.CoopInstrumentsNew__r.QuoteProduct__r.Quote__c;
            if( ccl.CoopInstrumentsNew__r.Measure_Calculate_Product__r.Measure_Calculate__c != null )originId = ccl.CoopInstrumentsNew__r.Measure_Calculate_Product__r.Measure_Calculate__c;
            if(ccl.CoopInstrumentsNew__r.InstrumentPolicy__r.InstrumentPolicy__c != null )originId =ccl.CoopInstrumentsNew__r.InstrumentPolicy__r.InstrumentPolicy__c;
            if(ccl.CoopInstrumentsNew__r.BloodSugarOrderDetail1__r.BloodSugarOrder__c  != null ) originId = ccl.CoopInstrumentsNew__r.BloodSugarOrderDetail1__r.BloodSugarOrder__c;

            o_cooptype = ccl.CoopInstrumentsNew__r.CoopType__c;



    		Boolean isAdd = ccl.AlterType__c == '新增合同仪器' || ccl.AlterType__c == '合作形式/价格变更'   ;
    		productName = isAdd ? ccl.Product__r.ProductName__c : ccl.ContractProduct__r.Product__r.ProductName__c ;
    		spec  = isAdd ? ccl.Product__r.Spec__c : ccl.ContractProduct__r.Product__r.Spec__c ;
    		nccode = isAdd ? ccl.Product__r.NCCode__c : ccl.ContractProduct__r.Product__r.NCCode__c ;
            cate1 = isAdd ? ccl.Product__r.Category1__c : ccl.ContractProduct__r.Product__r.Category1__c ;
    		cooptype = ccl.CooperateType__c;
    		changetype = ccl.AlterType__c ;
            shortName = ccl.Product__r.NCinvshortname__c;
            
    		num = ccl.ChangeQuantity__c ; 
    		originnum = ccl.ContractProduct__r.Quantity__c;
    		cannum = ccl.ContractProduct__r.DeliveryQuantity__c;

            //termial = ccl.ContractProduct__r.EndCustomer__r.Name;

            oppNo = ccl.ContractProduct__r.Opportunity__r.OppNo__c;

            oppName = ccl.ContractProduct__r.Opportunity__r.Name;

    		quoteId  = ccl.ContractProduct__r.QuoteProduct__r.Quote__c;
    		mcId = ccl.ContractProduct__r.Measure_Calculate_Product__r.Measure_Calculate__c;
    		policyId = ccl.ContractProduct__r.InstrumentPolicy__r.InstrumentPolicy__c;
            bloodId = ccl.ContractProduct__r.BloodSugarOrderDetail1__r.BloodSugarOrder__c ;
    	
    		if(ccl.ContractProduct__r.QuoteProduct__r.Quote__r.Name != null )relateName =ccl.ContractProduct__r.QuoteProduct__r.Quote__r.Name;
    		if( ccl.ContractProduct__r.Measure_Calculate_Product__r.Measure_Calculate__r.Name != null )relateName = ccl.ContractProduct__r.Measure_Calculate_Product__r.Measure_Calculate__r.Name;
    		if(ccl.ContractProduct__r.InstrumentPolicy__r.InstrumentPolicy__r.Name != null )relateName =ccl.ContractProduct__r.InstrumentPolicy__r.InstrumentPolicy__r.Name;
            if(ccl.ContractProduct__r.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name  != null ) relateName = ccl.ContractProduct__r.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name;

    		originPrice  = ccl.ContractProduct__r.SalesPrice__c;
    		adprice = ccl.AdjustSalesPrice__c;
    		reason = ccl.Reason__c ;
    		ismcadd = ccl.WhetherAddInstrument__c;

    		relatedMcId = ccl.RelatedMeasure__c;
    		relatedMcName = ccl.RelatedMeasure__r.Name ;
            relatedId = ccl.ContractProduct__r.Product__r.MatchingInstrument__c;

            cate0 = ccl.Product__r.Category0__c;
            enterway = ccl.EnterWay__c;

    	}

    	public ModifyBean(ContractProduct__c cp ){

    		cpId = cp.Id;
    		productId = cp.Product__c;
    		productName =cp.Product__r.ProductName__c;
            shortName = cp.Product__r.NCinvshortname__c;
    		spec = cp.Product__r.Spec__c;
            brand = cp.Product__r.Brand__c;
    		nccode = cp.Product__r.NCCode__c;
    		originnum = cp.Quantity__c;
            num = cp.Quantity__c;

            cate1=  cp.Product__r.Category1__c;
    		cannum = cp.DeliveryQuantity__c;

            cate0 = cp.Product__r.Category0__c;
            enterway = cp.EnterWay__c;
            adprice = cp.SalesPrice__c;

            termial = cp.EndCustomer__r.Name;
    	   
            oppNo = cp.Opportunity__r.OppNo__c;
            oppName = cp.Opportunity__r.Name;

            quoteId  = cp.QuoteProduct__r.Quote__c;
            mcId = cp.Measure_Calculate_Product__r.Measure_Calculate__c;
            policyId = cp.InstrumentPolicy__r.InstrumentPolicy__c;
            bloodId = cp.BloodSugarOrderDetail1__r.BloodSugarOrder__c ;
        
            if(cp.QuoteProduct__r.Quote__r.Name != null )relateName =cp.QuoteProduct__r.Quote__r.Name;

            if( cp.Measure_Calculate_Product__r.Measure_Calculate__r.Name != null )relateName = cp.Measure_Calculate_Product__r.Measure_Calculate__r.Name;
            if(cp.InstrumentPolicy__r.InstrumentPolicy__r.Name != null )relateName =cp.InstrumentPolicy__r.InstrumentPolicy__r.Name;
            if(cp.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name  != null ) relateName = cp.BloodSugarOrderDetail1__r.BloodSugarOrder__r.Name;

            changetype = cp.Contract__c != null ?'减少原合同仪器数量': '新增合同仪器';


    		cooptype = cp.CoopType__c;

    		originPrice  = cp.SalesPrice__c;

    	}


    	// public ModifyBean(Product__c p ){
    	// 	productId = p.Id;
    	// 	productName = p.ProductName__c;
     //        shortName = p.NCinvshortname__c;
     //        cate1 = p.Category1__c;
    	// 	spec = p.Spec__c;
    	// 	nccode = p.NCCode__c;
    	// 	//cooptype = 
    	// 	changetype = '新增合同仪器';
     //        relatedId = p.MatchingInstrument__c;
     //        cate0 = p.Category0__c;

    	// }

    }




}